//
//  ConversationsViewController.m
//  AAIM
//
//  Created by awh on 2019/11/24.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "ConversationsViewController.h"
#import "ConversationTableViewCell.h"
#import "ConversationSearchBar.h"
#import "ChatViewController.h"

#import "XLPopMenuViewSingleton.h"
#import "XLPopMenuViewModel.h"

#import "RichScanQRCodeViewController.h"
#import "SearchResultsVC.h"
#import "SearchFriendsViewController.h"
#import "PSWJoinGroupVC.h"

#import "CreateGroupChatVC.h"
#import "GroupNoticeVC.h"

#import "LiftIMClient.h"
#import "LiftIMChatManager.h"
#import "LiftIMSystemManger.h"
#import "ConversationListDataBase.h"
#import "ChatMessagesDataBase.h"
#import "GroupMessageDataBase.h"
#import "ConversationManager.h"

#import "BTMessageModel.h"
#import "TextMessageModel.h"
#import "VoiceMessageModel.h"
#import "ImageMessageModel.h"

#import "ContactRequestLogic.h"
#import "BillViewController.h"

#import "GroupInfoViewController.h"
#import "FriendsInfoViewController.h"

#import "DataTool.h"
#import "AttentionPublicViewController.h"
@interface ConversationsViewController ()<UITableViewDelegate,UITableViewDataSource,LiftIMChatMangerDelegate,IMSystemManagerDelegate>
@property (nonatomic , strong) NSMutableArray *items;
@property (nonatomic, strong) UITableView * conversationsTable;
@property (nonatomic, strong) NSMutableArray *dataSources;
@property (nonatomic, strong) MJTableViewNullDataView *nullDataView;
@property (nonatomic, assign) NSInteger sysMessage_tabbarNum;
@property (nonatomic, strong)NSMutableArray *systemDataSources;
@end
@implementation ConversationsViewController
@synthesize items = _items;

-(MJTableViewNullDataView*)nullDataView {
    if (!_nullDataView) {
        _nullDataView=[[MJTableViewNullDataView alloc]initWithFrame:CGRectMake(0,120, SCREEN_WIDTH, self.conversationsTable.frame.size.height-60)];
        _nullDataView.hidden=YES;
        _nullDataView.backgroundColor=[UIColor whiteColor];
    }
    [_nullDataView setCustomViewFrame:@"空状态" message:@"暂时没有会话消息"];
    return _nullDataView;
}

- (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
     [self loadDataFromDB];
     [self loadUnreadCountFromDB];

}
- (void)loadUnreadCountFromDB {
    //    NSInteger unreadCount = [[ConversationListDataBase shareConversationListDataBase] totalUnreadCount];
    NSInteger unreadCount = [[ConversationManager shareManager] totalUnreadCount];
    // 会话列表角标
    [[LoginManager shareLoginManager].mainTabBar setRedDotWithIndex:0 ValueInteger:unreadCount isShow:unreadCount];
    // 应用角标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:unreadCount];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[LiftIMClient sharedClient].chatManager addDelegate:self];
    [[LiftIMClient sharedClient].systemManager addDelegate:self];

    [self setUI];

   NSString * currentNum = [CacheTool readUserDefaults:[NSString stringWithFormat:@"system_tabbarNum_%@",[LoginManager shareLoginManager].userModel.fuuid]];
    if (![NSObject ldy_isEmpty:currentNum]) {
        if ([currentNum integerValue]>0) {
            _sysMessage_tabbarNum=[currentNum integerValue];
            [self setTabBarNum:[currentNum integerValue]];
        }
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RemoveRedDot) name:kMessageSystemRemoveRedDot object:nil];

}

- (void)loadDataFromDB {
    NSArray *array = [[ConversationManager shareManager] queryAllConversations];
    AAIMLog(@"数据===%@",array);
    NSMutableArray *sources = [NSMutableArray new];
    [array enumerateObjectsUsingBlock:^(BTMessageModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray<NSString *> *conponents = [obj.keyid componentsSeparatedByString:@"_"];
        if (conponents.count == 2) {
//            NSInteger type = [conponents[0] isEqualToString:@"friend"] ? 1 : [conponents[0] isEqualToString:@"group"] ? 2 : 0;
//            if (type == 0) { // 系统消息
//                [sources addObject:obj];
//            } else { // 好友或群消息
             [sources addObject:obj];
//            }
        }
    }];
    
    if (sources.count) {
        [self.dataSources  removeAllObjects];
        [self.dataSources addObjectsFromArray:sources];
    }
    if (self.dataSources && self.dataSources.count) {
        self.nullDataView.hidden = YES;
    } else {
        self.nullDataView.hidden = NO;
    }
    [self.conversationsTable reloadData];
    
}
#pragma mark - LiftIMChatMangerDelegate
- (void)messagesDidReceive:(NSArray<BTMessageModel *> *)messages {
    if (messages == nil || messages.count <= 0) return;
    [self handleReceiveMessage:messages.firstObject];
}
- (void)handleReceiveMessage:(BTMessageModel *)msg {

    if (msg.chatType == ChatTypeFriend || msg.chatType == ChatTypeGroup) { // 好友消息或群消息
        // 判断是否是自己的好友或群组
        NSInteger type = msg.chatType == ChatTypeFriend ? 1 : 2;
        NSString * friendOrGroupId = msg.chatType == ChatTypeFriend ? msg.rfuuid : msg.gId;
        /*数据库判断是否是自己的好友或者群*/
//        if (!isIn) return;
    } else {  // 系统消息
        
    }

    // 震动和声音
    //    [self vibrationAndVoice:msg];
    // 本地推送
    //    [self postLocalNNotification:msg];
    if (msg.msgtype == MessageTypeRecall) {
        // 聊天记录需要先删除原来的消息，再插入撤回的消息提示
        if (msg.chatType == ChatTypeFriend) {
            [[ChatMessagesDataBase shareChatMessagesDataBase] deleteMessage:msg];
            [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:msg];
        } else {
            [[GroupMessageDataBase shareGroupMessageDataBase] deleteMessage:msg];
            [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:msg];
        }
        
    } else {
        // 存储聊天记录
        if (msg.chatType != ChatTypeSystem) {
            // 存储数据库
//            msg.timestamp = [msg.createtime longLongValue];
            [[ConversationListDataBase shareConversationListDataBase] saveConversation:msg];
            msg.unreadCount = msg.messageType == MessageTypeRecall ? 0 : 1;
            [[ConversationManager shareManager] saveConversation:msg];
            
            [self addTimeMessageBefore:msg];
            if (msg.chatType == ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:msg];
            } else {
                msg.uid=msg.f_uuid.integerValue;
                [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:msg];
            }
        } else {
            AAIMLog(@"系统消息");
            
            if (msg.msgtype==7) {

                if (msg.type_id == SystemMessageApplyAddFriend)
                {
                    self.sysMessage_tabbarNum++;
                    //申请加好友 红点点
                    [self setTabBarNum:self.sysMessage_tabbarNum];
                    [[NSNotificationCenter defaultCenter]postNotificationName:kMessageSystemSetRedDot object:nil];
                    
                }else if (msg.type_id==SystemMessageAgreeAddFriend)
                {
                    //同意好友申请 刷数据
                    NSLog(@"首页添加会话列表");
                    
                    //申请加好友 红点点
                    self.sysMessage_tabbarNum++;
                    [self setTabBarNum:self.sysMessage_tabbarNum];
                    [[NSNotificationCenter defaultCenter]postNotificationName:kMessageSystemSetRedDot object:nil];
                    
                    // 存储数据库
                    msg.timestamp = [msg.createtime longLongValue];
                    msg.chatType=ChatTypeFriend;
                    msg.unreadCount=0;
                    [[ConversationListDataBase shareConversationListDataBase] saveConversation:msg];
                    [[ConversationManager shareManager] saveConversation:msg];
                    [[ConversationManager shareManager] reloadData];

                    [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
                        //刷新好友数据 ；
                        [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
                        
                        [self loadDataFromDB];
                    }];
                    [[SystemDataBase shareSystemDataBase] insertFriendSystemData:msg];
                }else if (msg.type_id==SystemMessageRefusedAddFriend)
                {   //拒绝好友
                    
                }else if (msg.type_id==SystemMessageShieldingFriend)
                {
                    //拉黑
                }else if (msg.type_id==SystemMessageDeleteGroupMember)
                {
                    //群移除
                    //被踢的是否是自己
                    if ([msg.rfuuid isEqualToString:[LoginManager shareLoginManager].userModel.fuuid]) {
                        [[UserDataBaseTool shareUserDataBaseTool] reloadData:2 Success:^(BOOL isOK) {
                            //刷新好友数据 ；
                            [ContactRequestLogic requestCheckGroupNameWithGroupID:msg.gId Success:^(NSDictionary * _Nonnull Dict) {
                                NSLog(@"%@",Dict);
                                NSLog(@"++++:%@",Dict[@"message"]);
                                // 存储数据库
                                msg.groupHead= Dict[@"data"][@"groupHead"];
                                msg.groupName= Dict[@"data"][@"groupName"];
                                msg.timestamp = [msg.createtime longLongValue];
                                msg.gId=[NSString stringWithFormat:@"%@",Dict[@"data"][@"id"]];
                                msg.chatType=ChatTypeGroup;
                                msg.unreadCount=0;
                                [[ConversationListDataBase shareConversationListDataBase] saveConversation:msg];
                                [[ConversationManager shareManager] saveConversation:msg];
                                [self loadDataFromDB];
                            } failure:^(NSString * _Nonnull errMsg) {
                                 NSLog(@"-------:%@",errMsg);
                            }];
                            [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemCreateGroup object:nil];
                        }];
                    }

                }
                if (msg.type_id == SystemMessageAuditJoinGroup || msg.type_id == SystemMessageAuditCreateGroup) {
                    NSLog(@"申请通过开新群");
                    // 存储数据库
                    msg.timestamp = [msg.createtime longLongValue];
                    msg.chatType=ChatTypeGroup;
                    msg.unreadCount=1;
                    [[ConversationListDataBase shareConversationListDataBase] saveConversation:msg];
                    [[ConversationManager shareManager] saveConversation:msg];
                    //聊天记录
                    [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:msg];
                    NSLog(@"通过申请加群");
                    [[UserDataBaseTool shareUserDataBaseTool] reloadData:2 Success:^(BOOL isOK) {
                        //刷新好友数据 ；
                        NSLog(@"刷新数据====");
                        [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemCreateGroup object:nil];
                        [self loadDataFromDB];
                        
                    }];
                }
                
                //存储系统消息  群通知 账单信息
                if (msg.type_id ==SystemMessageRefusedAddFriend || msg.type_id ==SystemMessageShieldingFriend || msg.type_id ==SystemMessageAgreeAddFriend || msg.type_id ==SystemMessageApplyAddFriend) {
                }else
                {
                    msg.timestamp = [msg.createtime longLongValue];
                    msg.chatType=ChatTypeSystem;
                    if (msg.type_id == SystemMessageApplyCreateGroup|| msg.type_id ==  SystemMessageAuditCreateGroup || msg.type_id ==  SystemMessageDeleteGroup || msg.type_id ==  SystemMessageApplyJoinGroup || msg.type_id ==  SystemMessageAuditJoinGroup || msg.type_id ==  SystemMessageRefusedJoinGroup ||msg.type_id ==  SystemMessageMemberExit || msg.type_id == SystemMessageDeleteGroupMember ) {
                        msg.receiveUid=1000;
                    }else if (msg.type_id==SystemMessagebill)
                    {
                        msg.receiveUid=1001;
                    }
                    msg.unreadCount =  1;
                    [[ConversationListDataBase shareConversationListDataBase] saveConversation:msg];
                    [[ConversationManager shareManager] saveConversation:msg];
                    [[ConversationManager shareManager] reloadData];
                   
                }
                // 保存群通知的数据
                if (msg.type_id == SystemMessageApplyCreateGroup|| msg.type_id ==  SystemMessageAuditCreateGroup || msg.type_id ==  SystemMessageDeleteGroup || msg.type_id ==  SystemMessageApplyJoinGroup || msg.type_id ==  SystemMessageAuditJoinGroup || msg.type_id ==  SystemMessageRefusedJoinGroup ) {
                    //群通知信息展示
                    [ContactRequestLogic requestCheckGroupNameWithGroupID:msg.gId Success:^(NSDictionary * _Nonnull Dict) {
                        NSLog(@"%@",Dict);
                        msg.head= Dict[@"data"][@"groupHead"];
                        msg.nickname= Dict[@"data"][@"groupName"];
                        [[SystemDataBase shareSystemDataBase] insertSystemData:msg];
                    } failure:^(NSString * _Nonnull errMsg) {
                        NSLog(@"-------:%@",errMsg);
                    }];
                }
            }
        }
    }
//    NSInteger count = self.navigationController.viewControllers.count;
//    long long deltT = [ChatTool shareChatTool].currentTimestamp - self.lastRefreshTime;
//    if (deltT >= 1 * 1000 && count == 1 && !self.isTouch && [LoginManager shareLoginManager].mainTabBar.selectedIndex == 0) {
        [self loadDataFromDB];
//        self.lastRefreshTime = [ChatTool shareChatTool].currentTimestamp;
        //        NSLog(@"刷新表格==============");
//    }
    [self loadUnreadCountFromDB];
}
/// 判断是否在数据源中加入时间
- (void)addTimeMessageBefore:(BTMessageModel *)msg {
    BTMessageModel *timeMsg = [BTMessageModel new];
    timeMsg.messageDirection = MessageDirectionSend;
    timeMsg.msgtype = MessageTypeTime;
    timeMsg.uid = [[LoginManager shareLoginManager].userModel.fuuid integerValue];
    timeMsg.timestamp = msg.timestamp;
    timeMsg.cid = msg.timestamp;
    timeMsg.mine = YES;
    timeMsg.msgtype = MessageTypeTime;
    timeMsg.username = [LoginManager shareLoginManager].userModel.nickname;
    timeMsg.rfuuid = msg.rfuuid;
    timeMsg.gId = msg.gId;
    timeMsg.type = msg.type;
    
    BTMessageModel *lastMsg = nil;
    if (msg.chatType == ChatTypeFriend) {
        lastMsg = [[ChatMessagesDataBase shareChatMessagesDataBase] recentlyMessageWithUid:[msg.rfuuid integerValue]];
    } else {
        lastMsg = [[GroupMessageDataBase shareGroupMessageDataBase] recentlyMessageWithGroupId:[msg.gId integerValue]];
    }
    //    BTIMLog(@"找到最后一条消息的时间戳====%lld", lastMsg.timestamp);
    
    if (lastMsg) {
        if (msg.timestamp - lastMsg.timestamp > 1 * 60 * 1000) {
            if (msg.chatType == ChatTypeFriend) {
                [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:timeMsg];
            } else {
                [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:timeMsg];
            }
        }
    } else {
        if (msg.chatType == ChatTypeFriend) {
            [[ChatMessagesDataBase shareChatMessagesDataBase] insertMessage:timeMsg];
        } else {
            [[GroupMessageDataBase shareGroupMessageDataBase] insertMessage:timeMsg];
        }
    }
}


#pragma mark - IMSystemManagerDelegate

- (void)socketConnectStatusDidChanged:(NSInteger)status {
    if (status == 2) {
        self.gk_navTitle=@"收取中...";
    } else if (status == 3) {
        self.gk_navTitle=@"会话";
    } else  {
        self.gk_navTitle=@"会话";
    }
}

#pragma mark - UI
-(void)setUI
{
    self.gk_navTitle=@"会话";
    self.gk_navLineHidden  = YES;

    [self.view  addSubview:self.conversationsTable];
//    [self.conversationsTable  addSubview:self.nullDataView];

    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.conversationsTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
//        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.top.equalTo(self.gk_navigationBar.mas_bottom);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"加 (1)"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnDidClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn sizeToFit];
    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    rightBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(10, 10, 10, 10);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.gk_navRightBarButtonItem = rightItem;
    
    // 表头
    ConversationSearchBar *headView = [ConversationSearchBar loadFromNib];
    headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
    [headView.topBtn addTarget:self action:@selector(searchContact:) forControlEvents:UIControlEventTouchUpInside];
    self.conversationsTable.tableHeaderView = headView;
    
}
#pragma mark - ButtonEvent

- (void)searchContact:(UIButton *)sender {
    SearchResultsVC * searchVC=[[SearchResultsVC alloc]init];
     searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
    
}
-(void)rightBtnDidClickAction:(UIButton*)sender
{
    [YCXMenu setTintColor:[UIColor whiteColor]];
    [YCXMenu setTitleFont:[UIFont systemFontOfSize:14]];
    [YCXMenu hasShadow];
    [YCXMenu setHasShadow:YES];
    [YCXMenu setSeparatorColor:KHEXCOLOR(@"#E0E0E0")];
    [YCXMenu setSelectedColor:KHEXCOLOR(@"#E0E0E0")];
    if ([YCXMenu isShow]){
        [YCXMenu dismissMenu];
    } else {
        [YCXMenu showMenuInView:self.view fromRect:CGRectMake(self.view.frame.size.width - 55, NavigationBarHeight-10, 40, 0) menuItems:self.items selected:^(NSInteger index, YCXMenuItem *item) {
            NSLog(@"点击的=%ld",index);
//            if ([LoginManager shareLoginManager].userModel.allow.integerValue == 1) {
//                [self showTipHudWithText:@"无权限"];
//                return;
//            }
//            NSLog(@"点击的itrm=%@",item);
            if(index==0){
                SearchFriendsViewController * searchVC = [[SearchFriendsViewController alloc]init];
                
                searchVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:searchVC animated:YES];
                
            }else if(index==1)
            {
                PSWJoinGroupVC*joinGroupVC=[[PSWJoinGroupVC alloc]init];
                joinGroupVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:joinGroupVC animated:YES];
                
                
            }else if (index==2)
            {
                CreateGroupChatVC * createVC=[[CreateGroupChatVC alloc]init];
                createVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:createVC animated:YES];
                
            }else if(index==3)
            {
                KWeakSelf;
                RichScanQRCodeViewController * scanVC = [[RichScanQRCodeViewController alloc]initWithQrType:MMScanTypeQrCode onFinish:^(NSString *result, NSError *error) {
                    NSLog(@"扫一扫结果=%@",result);
//                    http://111.229.229.86:8081/contact/joinGroup?groupCode=3669  群扫描结果
//                    127.0.0.1:8080/friend/addF?source=s&fuuid=226391897
                    if ([result containsString:@"route"]) {
                        NSDictionary * dic = [DataTool dictionaryWithJsonString:result];
                        [self attentionPublic:dic];
                    }else if ([result containsString:@"fuuid"]) {
                        if (!error){
                       NSArray * codeAry = [result componentsSeparatedByString:@"="];
                        //加好友
                        if (codeAry.count ==3) {
                         [weakSelf textCode:codeAry[2] withType:0];
                        }else{
                            for (NSString * strs in codeAry) {
                                BOOL isNum = [CommonTools isPureNumandCharacters:strs];
                                if (isNum) {
                                    [weakSelf textCode:strs withType:0];
                                }
                            }
                         }
                        }
                    }else if ([result containsString:@"groupCode"]){
                        if (!error) {
                            NSArray * codeAry = [result componentsSeparatedByString:@"="];
                            for (NSString * strs in codeAry) {
                                BOOL isNum = [CommonTools isPureNumandCharacters:strs];
                                if (isNum) {
                                    [weakSelf textCode:strs withType:1];
                                }
                            }
                        }
                    }
                     
                }];
                scanVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:scanVC animated:YES];
                
            }
        }];
    }
}
//扫二维码关注公众号
- (void)attentionPublic:(NSDictionary *)dic{
    AttentionPublicViewController * attentionVC = [[AttentionPublicViewController alloc]init];
    attentionVC.udid = dic[@"udid"];
    attentionVC.fuuid = dic[@"fuuid"];
    attentionVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:attentionVC animated:YES];
}

//扫二维码进群
-(void)textCode:(NSString *)code withType:(NSInteger)type
{
    if (type == 1) {
        GroupInfoViewController * groupVC = [[GroupInfoViewController alloc]init];
        groupVC.pageType = @"codePage";
        groupVC.groupID = code;
        groupVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:groupVC animated:YES];

    }else{
        FriendsInfoViewController * requestVC = [[FriendsInfoViewController alloc]init];
        requestVC.Fuuid = code;
        requestVC.type = @"search";
        requestVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:requestVC animated:YES];

        
    }
    
    
}

#pragma mark- tabViewlDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSources.count;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BTMessageModel * model =self.dataSources[indexPath.row];
    if (model.chatType == ChatTypeFriend) {
     NSInteger friendId = [[model.keyid componentsSeparatedByString:@"_"] lastObject].integerValue;
       ContactModel * friendModel= [[UserDataBaseTool shareUserDataBaseTool] queryFriends:[NSString stringWithFormat:@"%ld",friendId]];
        ChatViewController * chatVC=[[ChatViewController alloc]init];
        chatVC.chatType = ChatTypeFriend;
        chatVC.receiverId =[NSString stringWithFormat:@"%ld",friendId];
        chatVC.gk_navTitle=friendModel.nickname;
        chatVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chatVC animated:YES];
         
    }else if (model.chatType == ChatTypeGroup )
    {
        NSInteger groupId = [[model.keyid componentsSeparatedByString:@"_"] lastObject].integerValue;
        ChatViewController * chatVC=[[ChatViewController alloc]init];
        ContactModel * groupdModel= [[UserDataBaseTool shareUserDataBaseTool] queryGroup:[NSString stringWithFormat:@"%ld",groupId]];
        chatVC.chatType = ChatTypeGroup;
        if (groupdModel) {
            chatVC.receiverId =groupdModel.user_id;   //groupId
            chatVC.gk_navTitle=groupdModel.groupName;  //model.username
            chatVC.groupHead=groupdModel.groupHead;
            chatVC.groupName=groupdModel.groupName;
        }else
        {
            chatVC.receiverId =[NSString stringWithFormat:@"%ld",groupId];
            chatVC.gk_navTitle=model.username;
            chatVC.groupHead=model.head;
            chatVC.groupName=model.username;
        }
        chatVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:chatVC animated:YES];
         
    }else if (model.chatType == ChatTypeSystem)
    {
        //群通知
        if ([model.keyid isEqualToString:@"sys_1000"]) {
            GroupNoticeVC * vc = [[GroupNoticeVC alloc]init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (model.type_id == SystemMessagebill){
            BillViewController * billVC = [[BillViewController alloc]init];
            billVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:billVC animated:YES];
        }
        
    }
    // 更新未读消息数为0
    [[ConversationListDataBase shareConversationListDataBase] clearUnreadCount:model];
    // 清空At
    [[ConversationListDataBase shareConversationListDataBase] clearAtWithMessage:model];
//
//    if (indexPath.row == 0) {
//        GroupNoticeVC * vc = [[GroupNoticeVC alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }else if(indexPath.row == 1){
//        ChatViewController * chatVC=[[ChatViewController alloc]init];
//        chatVC.chatType = ChatTypeFriend;
////        chatVC.receiverId =
//        [self.navigationController pushViewController:chatVC animated:YES];
//    }else{
//        ChatViewController * chatVC=[[ChatViewController alloc]init];
//        [self.navigationController pushViewController:chatVC animated:YES];
//    }

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConversationTableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier:[ConversationTableViewCell cellIdentifier] forIndexPath:indexPath];
    if (!cell) {
        cell = [[ConversationTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[ConversationTableViewCell cellIdentifier]];
    }
    cell.message=self.dataSources[indexPath.row];
    return cell;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)){
    BTMessageModel *message = self.dataSources[indexPath.row];
    //删除
    UIContextualAction *zhidingAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"置顶" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {

    }];
    zhidingAction.backgroundColor = KHEXCOLOR(@"#E94634");
    
    //删除
    UIContextualAction *openRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"消息开启" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
     
//        completionHandler(YES);
    }];
    openRowAction.backgroundColor = KHEXCOLOR(@"#C6C5CA");
    
    //删除
    UIContextualAction *closeRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"消息关闭" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
       
//        completionHandler(YES);
    }];
    closeRowAction.backgroundColor = KHEXCOLOR(@"#C6C5CA");
    
    //删除
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        NSInteger uidOrGroupID = [message.keyid componentsSeparatedByString:@"_"][1].integerValue;
        [[ConversationListDataBase shareConversationListDataBase] deleteConversationWithKeyid:message.keyid];
        [[ConversationManager shareManager] deleteConversationWithKeyid:message.keyid];
        [[ConversationManager shareManager] reloadData];
        [self.dataSources removeObjectAtIndex:indexPath.row];
        [self loadDataFromDB];
        completionHandler(YES);
    }];
    deleteRowAction.backgroundColor = KHEXCOLOR(@"#C6C5CA");
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction,openRowAction,closeRowAction,zhidingAction]];
    config.performsFirstActionWithFullSwipe = NO;
    return config;
}
-(void)setTabBarNum:(NSInteger)num
{
    [[LoginManager shareLoginManager].mainTabBar setRedDotWithIndex:1 ValueInteger:num isShow:YES];
    [CacheTool saveUserDefaults:[NSString stringWithFormat:@"system_tabbarNum_%@",[LoginManager shareLoginManager].userModel.fuuid] dataObj:[NSString stringWithFormat:@"%ld",num]];
}
-(void)RemoveRedDot
{
    _sysMessage_tabbarNum=0;
}
#pragma mark - getter
- (UITableView *)conversationsTable {
    if (!_conversationsTable) {
        _conversationsTable = [[UITableView alloc] init];
        _conversationsTable.delegate = self;
        _conversationsTable.dataSource = self;
        _conversationsTable.tableFooterView = [UIView new];
        _conversationsTable.rowHeight = 60.0f;
        [_conversationsTable registerNib:[ConversationTableViewCell registerNib] forCellReuseIdentifier:[ConversationTableViewCell cellIdentifier]];
        _conversationsTable.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return _conversationsTable;
}

- (NSMutableArray *)dataSources {
    if (!_dataSources) {
        _dataSources = [NSMutableArray new];
    }
    return _dataSources;
}
- (NSMutableArray *)systemDataSources {
    if (!_systemDataSources) {
        _systemDataSources = [NSMutableArray new];
    }
    return _systemDataSources;
}
-(void)dealloc
{
    [[LiftIMClient sharedClient].chatManager removeDelegate:self];
    [[LiftIMClient sharedClient].systemManager removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (NSMutableArray *)items {
    if (!_items) {
        _items = [@[[YCXMenuItem menuItem:@"添加好友"
                                    image:[UIImage imageNamed:@"icon-添加好友"]
                                      tag:99
                                 userInfo:@{@"title":@"Menu"}],
                    [YCXMenuItem menuItem:@"口令进群"
                                    image:[UIImage imageNamed:@"icon-口令进群"]
                                      tag:100
                                 userInfo:@{@"title":@"Menu"}],
                    [YCXMenuItem menuItem:@"创建群组"
                                    image:[UIImage imageNamed:@"icon-创建群组"]
                                      tag:101
                                 userInfo:@{@"title":@"Menu"}],
                    [YCXMenuItem menuItem:@"扫一扫"
                                    image:[UIImage imageNamed:@"icon-扫一扫"]
                                      tag:102
                                 userInfo:@{@"title":@"Menu"}]
                    ] mutableCopy];
    }
    return _items;
}
- (void)setItems:(NSMutableArray *)items {
    _items = items;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
